package ca.usherbrooke.mainApp.view.newSimulation;

import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import ca.usherbrooke.utils.FormUtility;

public class EntityPropertyPanel extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final JTextField imageEntityProperty;
	private final JTextField imageEntityWidth;
	private final JTextField imageEntityHeight;
	private final JTextField imageEntityDefault;
	private final JTextField imageEntityPropertyName;
	private final JTextField imageEntityPropertyId;
	private final JButton selectEntityImageProperty;
	private final JButton createEntityFileProperty;
	private final JButton addPairNameId;

	private final FormUtility form;
	private final JPanel PropertyPanel;
	private final JPanel parent;
	private final JPanel listPanel;

	JList entityIdList;
	DefaultListModel entityIdListModel;
	JList entityNameList;
	DefaultListModel entityNameListModel;

	private final JFileChooser fileChooser;
	private Boolean entityIsCreated;
	private final String fileSeparator;

	public EntityPropertyPanel(JPanel par) {

		fileSeparator = Character.toString(File.separatorChar);
		entityIsCreated = false;
		parent = par;
		listPanel = new JPanel(new FlowLayout());

		form = new FormUtility();
		fileChooser = new JFileChooser();

		PropertyPanel = this;
		PropertyPanel.setLayout(new GridBagLayout());
		PropertyPanel.setBorder(BorderFactory
				.createTitledBorder("Entity Property"));
		imageEntityProperty = new JTextField();
		imageEntityWidth = new JTextField();
		imageEntityHeight = new JTextField();
		imageEntityDefault = new JTextField();
		imageEntityPropertyName = new JTextField();
		imageEntityPropertyId = new JTextField();
		selectEntityImageProperty = new JButton("Select Image");
		createEntityFileProperty = new JButton(" Create file");
		addPairNameId = new JButton("add pair");
		// list
		entityIdList = new JList();
		entityIdListModel = new DefaultListModel();
		entityIdList.setModel(entityIdListModel);

		entityNameList = new JList();
		entityNameListModel = new DefaultListModel();
		entityNameList.setModel(entityNameListModel);

		listPanel.add(entityNameList);
		listPanel.add(entityIdList);

		form.addLabel("Entity Image: ", PropertyPanel);
		form.addMiddleField(imageEntityProperty, PropertyPanel);
		form.addLastField(selectEntityImageProperty, PropertyPanel);

		form.addLabel("Entity Width: ", PropertyPanel);
		form.addMiddleField(imageEntityWidth, PropertyPanel);
		form.addLastField(new JLabel(""), PropertyPanel);

		form.addLabel("Entity Height: ", PropertyPanel);
		form.addMiddleField(imageEntityHeight, PropertyPanel);
		form.addLastField(new JLabel(""), PropertyPanel);

		form.addLabel("Entity Default ID: ", PropertyPanel);
		form.addMiddleField(imageEntityDefault, PropertyPanel);
		form.addLastField(new JLabel(""), PropertyPanel);

		form.addLabel("Name / ID: ", PropertyPanel);
		form.addMiddleField(imageEntityPropertyName, PropertyPanel);
		form.addLastField(imageEntityPropertyId, PropertyPanel);

		form.addLabel(addPairNameId, PropertyPanel);
		form.addMiddleField(listPanel, PropertyPanel);
		form.addLastField(new JLabel(""), PropertyPanel);

		form.addLabel(new JLabel(""), PropertyPanel);
		form.addMiddleField(createEntityFileProperty, PropertyPanel);
		form.addLastField(new JLabel(""), PropertyPanel);

		initListener();

	}

	private void initListener() {
		selectEntityImageProperty.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				setectEntityImage();
			}
		});

		createEntityFileProperty.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				createFile();
			}
		});

		addPairNameId.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				entityIdListModel.addElement(imageEntityPropertyId.getText());
				entityNameListModel.addElement(imageEntityPropertyName
						.getText());
				imageEntityPropertyId.setText(" ");
				imageEntityPropertyName.setText(" ");
			}
		});

	}

	protected void setectEntityImage() {
		int returnVal = fileChooser.showOpenDialog(this);
		File file = null;
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			file = fileChooser.getSelectedFile();
			imageEntityProperty.setText(file.getAbsolutePath());
		}

	}

	public void createFile() {

		Boolean entityImageNameIsSet = false;
		Boolean widthIsSet = true, heightIsSet = true, defalaultIdIsSet = true, pairIdIsSet = true, pairNameIsSet = true, pairIsSet = false;
		double width = -1, height = -1;
		String str = "", namePair = "";
		String nameIdPair = "";
		String imageName = "";
		int index = -1, imageId = -1, defaultId = -1;

		// validate image name
		imageName = imageEntityProperty.getText();
		if (!imageName.trim().equalsIgnoreCase(" ")) {
			index = imageName.lastIndexOf(".");
			if (index != -1) {
				entityImageNameIsSet = true;
				imageName = imageName.substring(imageName
						.lastIndexOf(fileSeparator) + 1);
			}
		}

		// validate entity width
		try {
			width = Double.parseDouble(imageEntityWidth.getText().trim());
		} catch (NumberFormatException e) {
			widthIsSet = false;
		}

		// validate entity height
		try {
			height = Double.parseDouble(imageEntityHeight.getText().trim());
		} catch (NumberFormatException e) {
			heightIsSet = false;
		}

		// validate default id
		try {
			defaultId = Integer.parseInt(imageEntityDefault.getText().trim());
		} catch (NumberFormatException e) {
			defalaultIdIsSet = false;
		}

		// ----------------------to see ----------------------------------------

		// validate name/id
		if (!entityIdListModel.isEmpty() && !entityNameListModel.isEmpty()
				&& pairNameIsSet && pairIdIsSet) {
			pairIsSet = true;
		}

		// ---------------------------------------------------------------------
		// validate simulation folder name
		String folder = ((NewSimulationPanel) parent).getSimulationName();
		File file = null;

		if (!folder.equalsIgnoreCase(" ")) {

			// validate entries
			if (entityImageNameIsSet && widthIsSet && heightIsSet
					&& defalaultIdIsSet && pairIsSet) {

				// get pair name and Id
				int idSize = entityIdListModel.getSize();
				int nameSize = entityNameListModel.getSize();
				nameIdPair = "";
				for (int i = 0, j = 0; (i < nameSize && j < idSize); i++, j++) {

					pairNameIsSet = false;
					namePair = (String) entityNameListModel.get(i);
					if (!namePair.trim().equalsIgnoreCase(" ")) {
						pairNameIsSet = true;
					}

					try {
						pairIdIsSet = true;
						imageId = Integer.parseInt((String) entityIdListModel
								.get(j));
					} catch (NumberFormatException e) {
						pairIdIsSet = false;
					}

					if (pairNameIsSet && pairIdIsSet) {
						nameIdPair += namePair + "=" + imageId + "\r\n";
					}

				}// end for

				str = "sprite_sheet_path_key=.." + fileSeparator + "imgs"
						+ fileSeparator + imageName + "\r\n"
						+ "sprite_sheet_entity_width=" + width + "\r\n"
						+ "sprite_sheet_entity_height=" + height + "\r\n"
						+ "default= " + defaultId + "\r\n" + nameIdPair;

				// create directory
				new File(((NewSimulationPanel) parent).getPropertyFolderRoot()
						+ fileSeparator + folder + fileSeparator + "props")
						.mkdirs();

				// create file
				file = new File(
						((NewSimulationPanel) parent).getPropertyFolderRoot()
								+ fileSeparator + folder + fileSeparator
								+ "props" + fileSeparator, "entity.txt");
				try {
					FileWriter fstream;
					boolean isCeated = file.createNewFile();

					if (isCeated) {
						entityIsCreated = true;
						((NewSimulationPanel) parent)
								.setEnableEntityPropertyButtton(false);
						fstream = new FileWriter(file);
						BufferedWriter out = new BufferedWriter(fstream);
						out.write(str);
						out.close();
						fstream.close();
					}
				} catch (IOException e) {
					JOptionPane.showMessageDialog(this, e.getMessage(),
							"error", JOptionPane.ERROR_MESSAGE);
				}
			}

		} else {
			// delete the directory
			deleteDir(file);
			JOptionPane.showMessageDialog(null,
					"simulation is not valide...Revalidate the entries",
					"Alert", JOptionPane.ERROR_MESSAGE);
		}
		parent.remove(this);
		parent.revalidate();
	}

	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// The directory is now empty so delete it
		return dir.delete();
	}

	public Boolean getEntityIsCreated() {
		return entityIsCreated;
	}

	public void setEntityIsCreated(Boolean entityIsCreated) {
		this.entityIsCreated = entityIsCreated;
	}
}
